package com.deng.Service.impl;

import com.deng.Service.RoleService;
import com.deng.Service.UserDetailService;
import com.deng.Service.UserService;
import com.deng.config.AllParamOfUser;
import com.deng.config.common.Paging;
import com.deng.config.common.TimeUtil;
import com.deng.mapper.UserMapper;
import com.deng.model.To.UserAndRoles;
import com.deng.model.User;
import com.deng.model.UserDetail;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @Author 邓小熙
 * @Date 2022/5/2 11:41
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserDetailService userDetailService;
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    //账号正常使用
    private static final int BE_USEING = 1 ;
    // 账号已停用
    private static final int OUT_OF_SERVICE = 0 ;
    /**
     * 通过名字查找用户
     * @param name
     * @return
     */
    @Override
    public User findUserByName(String name) {
        return userMapper.findUserByName(name);
    }

    /**
     * 通过用户ID查找用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }

    /**
     * 通过评论人的ID查找用户
     * @param comments_user
     * @return
     */
    @Override
    public User findUsersById(int comments_user) {
        return userMapper.findUserById(comments_user);
    }
    /**
     * 个人简介，通过名字查找用户
     * @param userName
     * @return
     */
    @Override
    public User findUsersByName(String userName) {
        return userMapper.findUsersByName(userName);
    }
    /**
     * 通过名字找作者
     * @param userName
     * @return
     */
    @Override
    public int findAuthorByName(String userName) {
        return userMapper.findAuthorByName(userName);
    }
    /**
     * 通过ID找作者
     * @param id
     * @return
     */
    @Override
    public String findUserNameById(int id) {
        return userMapper.findUserNameById(id);
    }
    /**
     * 后台用户完善信息
     * @param name
     * @return
     */
    @Override
    public AllParamOfUser getUserParam(String name) {
        AllParamOfUser allParamOfUser = new AllParamOfUser();

        User user = userMapper.findUsersByName(name);

        UserDetail userDetail = userDetailService.findUserDetailByUserName(name);

        allParamOfUser.setUsers(user);
        allParamOfUser.setUserDetail(userDetail);

        return allParamOfUser;
    }
    /**
     * 改变用户详情修改
     * @param allParamOfUser
     * @return
     */
    @Override
    public AllParamOfUser edictDetail(AllParamOfUser allParamOfUser) {
        return userMapper.edictDetail(allParamOfUser);
    }
    /**
     * 更新用户信息
     * @param imgMes
     * @param userName
     * @param realName
     * @param position
     * @param data
     * @param email
     * @param address
     * @param sketch
     * @return
     * @throws ParseException
     */
    @Override
    public int updateUserMes(String imgMes,
                             String userName,
                             String realName,
                             String position,
                             String data,
                             String email,
                             String address,
                             String sketch) throws ParseException {
        SimpleDateFormat sdf= TimeUtil.formatToYMD();
        java.util.Date date=sdf.parse(data);
        UserDetail userDetail = userDetailService.findUserDetailByUserName(userName);
        int userId = userService.findAuthorByName(userName);
        if(userDetail == null){
            // 查不到userdetail 说明还没有信息 执行insert操作
            UserDetail u1 = setDetail(userId,position,date,address,sketch);
            userDetailService.insertUserDetailByUserId(u1);
        }else {
            //可以查询到userdetail的信息站执行update操作
            UserDetail u2 = setDetail(userId,position,date,address,sketch);
            userDetailService.updateUserDetailByUserId(u2);
        }

        User users2 = setUserDetail(imgMes,realName,email);


       return userService.updateUserMes1(users2,userName);
    }

    /**
     * 更新用户详情
     * @param users
     * @param name
     * @return
     */
    @Override
    public int updateUserMes1(User users, String name) {
        return userMapper.updateUserMes(users,name);
    }

    private User setUserDetail(String imgMes,
                                String realName,
                                String email
    ){
        User users = new User();
        users.setEmail(email);
        users.setHead(imgMes);
        users.setReal_name(realName);
        return users;
    }

    private UserDetail setDetail(int userId,
                                 String position,
                                 java.util.Date data,
                                 String address,
                                 String sketch){
        UserDetail u1 = new UserDetail();
        u1.setUser_id(userId);
        u1.setAddress(address);
        u1.setBirthday(data);
        u1.setPosition(position);
        u1.setSketch(sketch);
        return u1;
    }

    /**
     * 显示所有人员（分页）
     * @param pageNum
     * @return
     */
    @Override
    public List<UserAndRoles> userAndRole(int pageNum) {
        // 固定 limit
        int limit = Paging.LIMIT.getValue() ;
        List<User> user = findAllUsers((pageNum-1) * limit,limit);
        return listSwap(user);
    }

    private List<UserAndRoles> listSwap(List<User> user){
        List<UserAndRoles> userAndRoles = Lists.newLinkedList();
        for (User u: user
        ) {
            String userName = u.getLogin_name();
            Set<String> roleSet =  roleService.findRoleByName(userName);
            String roleName = null;
            Iterator iterator = roleSet.iterator();
            while(iterator.hasNext())
            {
                roleName = (String) iterator.next();
            }
            UserAndRoles userAndRole = setValue(u,roleName);
            userAndRoles.add(userAndRole);
        }
        return userAndRoles;
    }

    private UserAndRoles setValue(User user, String roleName) {
        UserAndRoles userAndRoles = new UserAndRoles();
        userAndRoles.setUserId(user.getId());
        userAndRoles.setUserName(user.getLogin_name());
        userAndRoles.setCreateTIme(user.getCreate_time());
        userAndRoles.setEmail(user.getEmail());
        int statusNumber = user.getStatus();
        if(statusNumber == OUT_OF_SERVICE ){
            userAndRoles.setStatus("已停用");
        }
        if(statusNumber == BE_USEING)
        {
            userAndRoles.setStatus("正在使用");
        }
        userAndRoles.setRoleName(roleName);
        return userAndRoles;
    }
    /**
     * 分页查询所有用户
     * @param page
     * @param limit
     * @return
     */
    @Override
    public List<User> findAllUsers(int page, int limit) {
        return userMapper.findAllUsersListLimit(page, limit);
    }
    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<User> findAllUsers() {
        return userMapper.findAllUsersList();
    }
    /**
     * 人员状态修改
     * @param review
     * @param status
     * @param userId
     * @return
     */
    @Override
    public int updateUserStatus(String review, String status, int userId) {
        int statusInt = Integer.parseInt(status);
        return userMapper.updateUserStatus(review, statusInt, userId);
    }
    /**
     * 后台文章审查中的文章发表博主部分信息
     * @param id
     * @return
     */
    @Override
    public User checkUserMes(int id) {
        return insurePrivacyMes(userMapper.findUserById(id));
    }

    /**
     * 确保只提取到非隐私信息
     * @param users
     * @return
     */
    private User insurePrivacyMes(User users){
        User privacy = new User();
        privacy.setId(users.getId());
        privacy.setLogin_name(users.getLogin_name());
        privacy.setEmail(users.getEmail());
        privacy.setHead(users.getHead());
        privacy.setStatus(users.getStatus());
        return privacy;
    }
    /**
     * 改密码
     * @param userName 用户名
     * @param newPassWord 新密码
     * @param oldPassWord 旧密码
     * @return 1
     */
    @Override
    public int updateUserPass(String userName, String newPassWord, String oldPassWord) {
        return userMapper.updateUserPass(userName, newPassWord, oldPassWord);
    }

}
